<?php

namespace App\Models;

use http\Env\Request;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class CompanyCity extends Model
{
    use HasFactory;
    protected $table = 'company_cities';

    public $timestamps = false;

    public $guarded = [];

    public static function cities($companyId,$cityType, $goodsSn = '') {
        // 获取省份
        $provinces = CompanyCity::where('company', $companyId)
            ->where('type', $cityType)
            ->select('province_id as code', 'province_name as name')
            ->groupBy('province_id')
            ->get();

        $validCities = $goodsSn ? Goods::where('sn', $goodsSn)->value('cities') : '';
        $validCities = explode(",", $validCities);
        $validCities = array_filter($validCities);
        // 获取城市
        $allProvinces = [];
        foreach ($provinces as $province) {
            $where = ['company' => $companyId,'province_id' => $province->code];

            if ($companyId == Company::TZL && $goodsSn) {
                $db = CompanyCity::where($where);
                if (count($validCities) > 0) {
                    $db->whereIn('city_id', $validCities);
                }
                $cities = $db->select('city_id as code', 'city_name as name')->get();
            } else {
                $cities = CompanyCity::where($where)->select('city_id as code', 'city_name as name')->get();
            }

            // 从门店获取
            foreach ($cities as $city) {
                $regions = Shop::where('city', $city->code)->where('company', $companyId)->pluck('region')->toArray();
                $regions = array_unique($regions);
                $regions = City::whereIn('id', $regions)->select('id as code', 'name')->get();
                $city->children = $regions;
            }
            $province->children = $cities;
            if (count($cities) >0) {
                array_push($allProvinces, $province);
            }
        }

        return $allProvinces;
    }
}
